package cuit.web;

import com.mysql.jdbc.StringUtils;

import cuit.domain.Blog;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.*;
import javax.servlet.http.*;

import cuit.service.BlogService;

public class BlogController extends HttpServlet{ 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1530365362741956096L;
	private BlogService blogService;
    private static String INSERT_OR_EDIT = "/blog.jsp";
    private static String LIST_BLOG = "/listBlog.jsp";
    
	public BlogController(){
		super();
		blogService = new BlogService();
	}
	
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forward="";
        String action = request.getParameter("action");
 
        if (action.equalsIgnoreCase("delete")){
            String blogId = request.getParameter("blogId");
            if(!StringUtils.isNullOrEmpty(blogId)){
                blogService.delete(Long.parseLong(blogId));
                forward = LIST_BLOG;
                request.setAttribute("blogs", blogService.listAll());    	
            } 
        } else if (action.equalsIgnoreCase("edit")){
            forward = INSERT_OR_EDIT;
            String blogId = request.getParameter("blogId");
            Blog blog = blogService.getBlogById(blogId);
            request.setAttribute("blog", blog);
        } else if (action.equalsIgnoreCase("listblog")){
            forward = LIST_BLOG;
            request.setAttribute("blogs", blogService.listAll());
        } else {
            forward = INSERT_OR_EDIT;
        }
 
        RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Blog blog = new Blog();
        blog.setTitle(request.getParameter("title"));
        blog.setContent(request.getParameter("content"));
        try {
            Date publish = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("publish"));
            System.out.println("发布日期："+ publish);
            blog.setPublish(publish);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String blogId = request.getParameter("blogId");
        if(StringUtils.isNullOrEmpty(blogId))
        {
        	blogService.insert(blog);
        }
        else
        {
            blog.setId(Long.parseLong(blogId));
            blogService.update(blog);
        }
        RequestDispatcher view = request.getRequestDispatcher(LIST_BLOG);
        request.setAttribute("blogs", blogService.listAll());
        view.forward(request, response);
    }
}
